package com.netease.examination.web.seller;

import com.alibaba.fastjson.JSON;
import com.netease.examination.dto.ResultDTO;
import com.netease.examination.model.Goods;
import com.netease.examination.service.QiniuService;
import com.netease.examination.service.seller.GoodsService;
import com.netease.examination.util.ExaminationUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.util.StreamUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;

/**
 * designed by destiny
 *
 * @author destiny
 *         e-mail destinywk@163.com
 *         github https://github.com/DestinyWang
 *         oschina https://git.oschina.net/destinywk
 * @version JDK 1.8.0_101
 * @since 2017/3/30 22:16
 */
@Controller
public class GoodsController {

    private static final Logger LOGGER = LoggerFactory.getLogger(GoodsController.class);

    @Resource
    private QiniuService qiniuService;

    @Resource
    private GoodsService goodsService;

    /**
     * 上传图片
     *
     * POST /uploadImage/ HTTP/1.1
     * Content-Type: multipart/form-data; charset=utf-8; boundary=__X_PAW_BOUNDARY__
     * Host: localhost:8080
     * Connection: close
     * User-Agent: Paw/3.0.12 (Macintosh; OS X/10.12.0) GCDHTTPRequest
     * Content-Length: 112424

     * --__X_PAW_BOUNDARY__
     * Content-Disposition: form-data; name="file"; filename="DSCF1770.jpg"
     * Content-Type: image/jpeg
     * (二进制流)
     *
     * @param file
     * @return
     */
    @RequestMapping(path = {"/uploadImage/"}, method = RequestMethod.POST,
            produces = {"application/json;charset=UTF-8"})
    @ResponseBody
    @CrossOrigin
    public String uploadImageByFile(@RequestParam("file") MultipartFile file) {
        try {
            String fileUrl = qiniuService.saveImageByFile(file);
            if (fileUrl == null) {
                return JSON.toJSONString(new ResultDTO(false, "上传失败"));
            }
            return JSON.toJSONString(new ResultDTO<>(true, new StringBuilder("上传成功")));
        } catch (Exception e) {
            LOGGER.error("图片上传失败:" + e.getMessage());
            return JSON.toJSONString(new ResultDTO(false, "上传失败"));
        }
    }



    /**
     * 从服务器获取图片
     * 不会任何显式的数据返回
     * 直接将图片的二进制流封装进HTTP响应正文中
     *
     * HTTP/1.1 200 OK
     * Server: Apache-Coyote/1.1
     * Content-Type: image/jpeg;charset=UTF-8
     * Transfer-Encoding: chunked
     * Date: Mon, 10 Oct 2016 10:16:28 GMT
     * Connection: close
     * (二进制流)
     *
     * @param imageName 图片名称
     * @param response HTTP响应对象
     */
    @RequestMapping(path = {"/image"}, method = RequestMethod.GET)
    @ResponseBody
    @CrossOrigin
    public void getImage(@RequestParam("name") String imageName,
                           HttpServletResponse response) {
        response.setContentType("image/png");
        try {
            StreamUtils.copy(new FileInputStream(
                    new File(ExaminationUtil.LOCAL_IMAGE_DIR + imageName)),
                    response.getOutputStream());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    @RequestMapping(path = {"/addGoods/"}, produces = {"application/json;charset=UTF-8"})
    @ResponseBody
    @CrossOrigin
    public String insertGoods(@RequestParam("title")String title,
                              @RequestParam("summary") String summary,
                              @RequestParam("imgUrl") String imgUrl,
                              @RequestParam("content") String content,
                              @RequestParam("price") Double price) {
        Goods goods = new Goods(title, summary, imgUrl, content, price, 0);
        Integer count = goodsService.insertGoods(goods);
        if (count == 1) {
            return JSON.toJSONString(new ResultDTO<>(true, new StringBuilder("添加成功")));
        } else {
            return JSON.toJSONString(new ResultDTO<>(false, "添加失败"));
        }
    }

    /**
     * 商品展示详情页
     *
     * @param id    商品主键
     * @return      展示结果
     */
    @RequestMapping(path = {"/show"}, produces = {"application/json;charset=UTF-8"})
    @ResponseBody
    @CrossOrigin
    public String goodsDetail(@RequestParam("id") Long id) {
        Goods goods = goodsService.getById(id);
        if (goods == null) {
            return JSON.toJSONString(new ResultDTO(false, "该商品不存在"));
        } else {
            return JSON.toJSONString(new ResultDTO<Goods>(true, goods));
        }
    }

    /**
     * 商品修改页
     *
     * @param id
     * @return
     */
    @RequestMapping(path = {"/edit"}, produces = {"application/json;charset=UTF-8"})
    @ResponseBody
    @CrossOrigin
    public String updateById(@RequestParam("id") Long id) {
        return goodsDetail(id);
    }

    @RequestMapping(path = {"/editSubmit"}, produces = {"application/json;charset=UTF-8"})
    @ResponseBody
    @CrossOrigin
    public String editSubmit(@RequestParam("id") Long id,
                             @RequestParam("title")String title,
                             @RequestParam("summary") String summary,
                             @RequestParam("imgUrl") String imgUrl,
                             @RequestParam("content") String content,
                             @RequestParam("price") Double price) {
        Goods goods = new Goods();
        goods.setId(id);
        goods.setTitle(title);
        goods.setSummary(summary);
        goods.setImgUrl(imgUrl);
        goods.setContent(content);
        goods.setPrice(price);

        Integer count = goodsService.updateById(goods);
        if (count == null || count == 0) {
            return JSON.toJSONString(new ResultDTO<>(false, "修改失败"));
        } else {
            return JSON.toJSONString(new ResultDTO<>(true, goods));
        }
    }

}
